// 个人中心相关变量
let currentUser = null;
let currentSection = 'profile';

// 加载用户资料
async function loadUserProfile() {
    try {
        const response = await fetch('/api/user/profile');
        if (!response.ok) {
            throw new Error('获取用户资料失败');
        }
        currentUser = await response.json();
        loadSection(currentSection);
    } catch (error) {
        console.error('加载用户资料失败:', error);
        showMessage('profile-message', '加载用户资料失败，请重试', true);
    }

    const section = new URLSearchParams(window.location.search).get('section') || 'profile';
    switchSection(section);
}

// 切换内容区域
function switchSection(section) {
    currentSection = section;

    // 更新菜单项状态
    document.querySelectorAll('.profile-menu-item').forEach(item => {
        item.classList.toggle('active', item.dataset.section === section);
    });

    // 更新内容区域显示
    document.querySelectorAll('.profile-section').forEach(section => {
        section.classList.toggle('active', section.id === `${currentSection}-section`);
    });

    // 加载对应区域的内容
    loadSection(section);
}

// 加载区域内容
async function loadSection(section) {
    switch (section) {
        case 'profile':
            await loadProfile();
            break;
        case 'published':
            await loadPublishedProducts();
            break;
        case 'favorites':
            await loadFavoriteProducts();
            break;
        case 'transactions':
            await loadTransactions();
            break;
    }
}

// 加载个人资料界面
async function loadProfile() {

}

// 加载已发布商品
async function loadPublishedProducts() {
    try {
        const response = await fetch('/api/user/profile');
        if (!response.ok) {
            throw new Error('获取已发布商品失败');
        }
        const data = await response.json();
        updateProductsGrid(data.products || [], 'published-section');
    } catch (error) {
        console.error('加载已发布商品失败:', error);
        showMessage('profile-message', '加载已发布商品失败，请重试', true);
    }
}

// 加载收藏商品
async function loadFavoriteProducts() {
    try {
        const response = await fetch('/api/user/profile');
        if (!response.ok) {
            throw new Error('获取收藏商品失败');
        }
        const data = await response.json();
        updateProductsGrid(data.favorites || [], 'favorites-section');
    } catch (error) {
        console.error('加载收藏商品失败:', error);
        showMessage('profile-message', '加载收藏商品失败，请重试', true);
    }
}

// 加载交易记录
async function loadTransactions() {
    try {
        const response = await fetch('/api/user/profile');
        if (!response.ok) {
            throw new Error('获取交易记录失败');
        }
        const data = await response.json();
        updateTransactionsList(data.transactions || []);
    } catch (error) {
        console.error('加载交易记录失败:', error);
        showMessage('profile-message', '加载交易记录失败，请重试', true);
    }
}

// 更新商品网格
function updateProductsGrid(products, sectionId) {
    const container = document.querySelector(`#${sectionId} .products-grid`);
    if (!products || products.length === 0) {
        container.innerHTML = '<div class="no-items">暂无商品</div>';
        return;
    }

    container.innerHTML = products.map(product => `
        <div class="product-card" onclick="window.location.href='/product.html?id=${product.id}'">
            <img src="${product.images[0] || '/images/placeholder.jpg'}" alt="${product.name}" class="product-image">
            <div class="product-info">
                <h3 class="product-title">${product.name}</h3>
                <p class="product-description">${product.description}</p>
                <div class="product-price">¥${product.price.toFixed(2)}</div>
            </div>
        </div>
    `).join('');
}

// 更新交易记录列表
function updateTransactionsList(transactions) {
    const container = document.querySelector('#transactions-section .transaction-list');
    if (!transactions || transactions.length === 0) {
        container.innerHTML = '<div class="no-items">暂无交易记录</div>';
        return;
    }

    container.innerHTML = transactions.map(transaction => `
        <div class="transaction-item">
            <div class="transaction-header">
                <span class="transaction-title">${transaction.product_name}</span>
                <span class="transaction-date">${new Date(transaction.created_at).toLocaleString()}</span>
            </div>
            <div class="transaction-details">
                <p>交易金额: ¥${transaction.amount.toFixed(2)}</p>
                <p>交易状态: ${transaction.status}</p>
            </div>
        </div>
    `).join('');
}

document.addEventListener('DOMContentLoaded', function () {
    loadUserProfile();

    // 1. 自我描述编辑功能
    const editDescBtn = document.getElementById('editDescBtn');
    const saveDescBtn = document.getElementById('saveDescBtn');
    const cancelDescBtn = document.getElementById('cancelDescBtn');
    const descEditGroup = document.getElementById('descEditGroup');
    const descInput = document.getElementById('descInput');
    const userDescText = document.getElementById('userDescText');

    editDescBtn.addEventListener('click', function () {
        descInput.value = userDescText.textContent;
        userDescText.parentElement.style.display = 'none';
        descEditGroup.style.display = 'block';
    });

    saveDescBtn.addEventListener('click', function () {
        userDescText.parentElement.style.display = 'flex';
        descEditGroup.style.display = 'none';
        edit_user_description(descInput.value);
    });

    cancelDescBtn.addEventListener('click', function () {
        userDescText.parentElement.style.display = 'flex';
        descEditGroup.style.display = 'none';
    });

    // 2. 交易地址编辑功能
    const editAddressBtn = document.getElementById('editAddressBtn');
    const saveAddressBtn = document.getElementById('saveAddressBtn');
    const cancelAddressBtn = document.getElementById('cancelAddressBtn');
    const addressEditGroup = document.getElementById('addressEditGroup');
    const addressInput = document.getElementById('addressInput');
    const addressText = document.getElementById('addressText');

    editAddressBtn.addEventListener('click', function () {
        addressInput.value = addressText.textContent;
        addressText.parentElement.style.display = 'none';
        addressEditGroup.style.display = 'block';
    });

    saveAddressBtn.addEventListener('click', function () {
        addressText.parentElement.style.display = 'flex';
        addressEditGroup.style.display = 'none';
        edit_user_address(addressInput.value.trim());
    });

    cancelAddressBtn.addEventListener('click', function () {
        addressText.parentElement.style.display = 'flex';
        addressEditGroup.style.display = 'none';
    });

    // 3. 头像上传功能
    const avatarUpload = document.getElementById('avatarUpload');
    const changeAvatarBtn = document.getElementById('changeAvatarBtn');
    const avatarPreview = document.querySelector('.profile-avatar');

    changeAvatarBtn.addEventListener('click', function () {
        avatarUpload.click();
    });

    avatarUpload.addEventListener('change', function (e) {
        const file = e.target.files[0];
        if (file && file.type.match('image.*')) {
            upload_avatar(file);
        }
    });

    // 4. 发布商品按钮
    document.getElementById('publishBtn').addEventListener('click', function () {
        // window.location.href = "/publish";
        window.location.href = "/publish.html";
    });

    load_user_info();
});

async function load_user_info() {
    const response = await fetch('/api/user/profile',
        {
            headers: {
                'Content-Type': 'application/json'
            }
        }
    );
    const data = await response.json();
    // 头像
    document.getElementById('avatar').src = data.avatar;
    // 昵称
    document.getElementById('nickname').textContent = data.nickname;
    // 邮箱
    document.getElementById('userEmail').textContent = data.email;
    // 自我描述
    document.getElementById('userDescText').textContent = data.description;
    // 交易地址
    document.getElementById('addressText').textContent = data.address;
}

async function upload_avatar(file) {
    const formData = new FormData();
    formData.append('image', file);
    const response = await fetch('/api/user/avatar', {
        method: 'POST',
        body: formData
    });
    const data = await response.json();
    if (data.status == 'success') {
        const avatarPreview = document.querySelector('.profile-avatar');
        avatarPreview.src = data.avatar;
    } else {
        alert(data.message);
    }
}

async function edit_user_address(address) {
    const response = await fetch('/api/user/address', {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: JSON.stringify({ address })
    });
    const data = await response.json();
    if (data.status == 'success') {
        document.getElementById('addressText').textContent = address;
    } else {
        alert(data.message);
    }
}

async function edit_user_description(description) {
    const response = await fetch('/api/user/description', {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: JSON.stringify({ description })
    });
    const data = await response.json();
    if (data.status == 'success') {
        document.getElementById('userDescText').textContent = description;
    } else {
        alert(data.message);
    }
}